<?php
/**
 * 根据登录用户的角色以及Permission配置，设置用户权限
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Auth.php 1082 2011-12-09 09:27:48Z mmxie $
 */
class IG_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{

    /**
     * 公开的
     */
    private $_noacl = array(
        'module' => 'default',
        'controller' => 'auth',
        'action' => 'no-auth'
    );

    /**
     * 进行身份验证
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $auth  = Zend_Auth::getInstance();
        $acl   = IG_Acl::getInstance();

        $controller = $request->controller;
        $module = $request->module;
        $action = $request->action;

        $moduleLevel = $module;
        $controllerLevel = $moduleLevel . '_' . $controller;
        $actionLevel = $controllerLevel . '_' . $action;

        $resource = $actionLevel;
        if ($acl->has($resource)) {
            if (!$auth->hasIdentity()) {
                if (!$acl->isAllowed('guest', $resource)) {
                    header("Location:/auth/login");
                    exit;
                }
            } else {
                $view = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer')->view;
                $view->assign('identity', $auth->getIdentity());

                //增加未分配角色的用户权限
                $roles = $auth->getIdentity()->getRoles()->toArray();
                array_push($roles, array('name' => 'guest'), array('name' => 'base'));
                foreach ($roles as $role) {
                    if ($acl->isAllowed($role['name'], $resource)) {
                        return ;
                    }
                }

                $request->setModuleName($this->_noacl['module'])
                        ->setControllerName($this->_noacl['controller'])
                        ->setActionName($this->_noacl['action']);
            }
        }
    }
}